/* eslint-disable react-hooks/rules-of-hooks */
import { NavBar, SearchBar } from 'antd-mobile'
import React, { useState } from 'react'
import styles from './css/city.module.css'
import { useLoaderData, useNavigate } from 'react-router-dom'
import City from './computents/City'
import { CityApi, getCityApi, SearchCityApi } from '../../api/city'
import { useDispatch } from 'react-redux'
import { setCity } from '../../store/slice/ticketSlice'
import SaerchCity from './computents/SaerchCity'
import SearchHistory from './computents/SearchHistory'

function index() {
    let nav=useNavigate()
    const loaderDate=useLoaderData()

    let dispatch=useDispatch()
    const saveCity=(propName,city)=>{
        dispatch(setCity({propName,city}))
        nav(-1)
    }
    let [serachCity,setsearchCity]=useState([])
    let [kw,setKw]=useState('')
    const changeFn=(kw)=>{
        setKw(kw)
        if(kw.length!==0){
            search(kw)
        }else{
            setsearchCity([])
        }
    }
    const search=async(kw)=>{
        const {data:res}=await SearchCityApi(kw)
        
        setsearchCity(res)
    }
  return (
    <div className={styles.box}>
      <NavBar onBack={()=>nav(-1)}>
        <SearchBar placeholder='如北京' onChange={changeFn}/>
      </NavBar>
      <div style={{display:kw.length===0?'none':'block'}}>
        <SaerchCity  saveCity={saveCity} list={serachCity}/>
        <SearchHistory saveCity={saveCity}/>
        </div>
       <City saveCity={saveCity} citywz={loaderDate.citywz} hotCities={loaderDate.hotCities} cityList={loaderDate.cityList} />
      
    </div>
  )
}

export default index

export const loader=async()=>{
    const {data:res}=await CityApi()
    console.log('res',res);
    const {data:res1}=await getCityApi()
    console.log('res1',res1);
    
    return {citywz:res.city,hotCities:res1.hotCities,cityList:res1.cityList}
}